package com.example.bookkeeping_book.utility;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.example.bookkeeping_book.domain.AccountBook;
import com.example.bookkeeping_book.domain.Consumer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Utility {
    private static SQLiteDatabase db;
    private static ContentValues values = new ContentValues();

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public static List<String> getInfo(InputStream is) throws IOException {
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        String json = new String(buffer, "utf-8");
        Gson gson = new Gson();
        Type listType = new TypeToken<List<String>>() {
        }.getType();
        List<String> strings = gson.fromJson(json, listType);
        return strings;
    }

    public static void insert(MySqlite sqlite, AccountBook accountBook) {
        db = sqlite.getWritableDatabase();

        values.put("consumerId", accountBook.getConsumerId());
        values.put("consumption_item", accountBook.getConsumption_item());
        values.put("amount", accountBook.getAmount());
        values.put("date", accountBook.getDateToString());
        values.put("remarks", accountBook.getRemarks());

        db.insert("account", null, values);
        values.clear();
        db.close();
    }

    public static ArrayList<AccountBook> selectAll(MySqlite sqlite) {
        ArrayList<AccountBook> accountBooks = new ArrayList<>();
        db = sqlite.getReadableDatabase();
        Cursor cursor = db.query("account", null, null, null, null, null, new String("date desc"));
        if (cursor.getCount() == 0) {

        } else {
            cursor.moveToFirst();
            AccountBook accountBook = new AccountBook(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getDouble(3), cursor.getString(4), cursor.getString(5));
            accountBooks.add(accountBook);
            while (cursor.moveToNext()) {
                accountBook = new AccountBook(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getDouble(3), cursor.getString(4), cursor.getString(5));
                accountBooks.add(accountBook);
            }
        }
        cursor.close();
        db.close();
        return accountBooks;
    }

    public static AccountBook selectAccountBookById(MySqlite sqlite, int id) {
        AccountBook accountBook = null;
        db = sqlite.getReadableDatabase();
        Cursor cursor = db.query("account", null, "id=?", new String[]{id + ""}, null, null, null);
        if (cursor.getCount() == 0) {

        } else {
            cursor.moveToFirst();
            accountBook = new AccountBook(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getDouble(3), cursor.getString(4), cursor.getString(5));

        }
        cursor.close();
        db.close();
        return accountBook;
    }

    public static void deleteAccountBookItem(MySqlite sqlite, int id) {
        db = sqlite.getWritableDatabase();
        db.delete("account", "id=?", new String[]{id + ""});
        db.close();
    }

    public static ArrayList<Consumer> selectAllConsumer(MySqlite sqlite) {
        ArrayList<Consumer> consumers = new ArrayList<>();
        db = sqlite.getReadableDatabase();
        Cursor cursor = db.query("consumer", null, null, null, null, null, null);
        if (cursor.getCount() == 0) {

        } else {
            cursor.moveToFirst();
            Consumer consumer = new Consumer(cursor.getInt(0), cursor.getString(1));
            consumers.add(consumer);
            while (cursor.moveToNext()) {
                consumer = new Consumer(cursor.getInt(0), cursor.getString(1));
                consumers.add(consumer);
            }
        }
        cursor.close();
        db.close();
        return consumers;
    }


    public static String selectNameById(MySqlite sqlite, int id) {
        String name = "";
        db = sqlite.getReadableDatabase();
        Cursor cursor = db.query("consumer", null, "id=?", new String[]{id + ""}, null, null, null);
        if (cursor.getCount() == 0) {

        } else {
            cursor.moveToFirst();
            name = cursor.getString(1);
        }
        cursor.close();
        db.close();
        if (name == "")
            return "未知";
        return name;
    }

    public static void insert(MySqlite sqlite, String name) {
        db = sqlite.getWritableDatabase();
        values.put("name", name);
        db.insert("consumer", null, values);
        values.clear();
        db.close();
    }

    public static boolean deleteConsumer(MySqlite sqlite, int id) {
        if (id == 1)
            return false;
        db = sqlite.getWritableDatabase();
        db.delete("consumer", "id=?", new String[]{id + ""});
        db.close();
        return true;
    }

    public static void updateBudget(MySqlite sqlite, String s) {
        db = sqlite.getWritableDatabase();
        values.put("budget", Double.parseDouble(s));
        db.update("budget", values, "id =?", new String[]{"0"});
        values.clear();
        db.close();

    }

    public static double selectBudget(MySqlite sqlite) {
        double s = 0;
        db = sqlite.getReadableDatabase();
        Cursor cursor = db.query("budget", null, null, null, null, null, null);
        if (cursor.getCount() == 0) {
            return 0;
        } else {
            cursor.moveToFirst();
            s = cursor.getDouble(1);
        }
        cursor.close();
        db.close();
        return s;
    }

    public static boolean saveUserInfo(Context context, String account, String password, boolean isCheck) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("account", account);
        editor.putString("password", password);
        if (isCheck)
            editor.putString("isCheck", "isCheck");
        else
            editor.putString("isCheck", "");
        editor.commit();

        return true;


    }

    public static Map<String, String> getUserInfo(Context context) {

        Map<String, String> userMap = new HashMap<>();

        SharedPreferences sharedPreferences = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        String account = sharedPreferences.getString("account", "");
        String password = sharedPreferences.getString("password", "");
        String isCheck = sharedPreferences.getString("isCheck", "");
        userMap.put("account", account);
        userMap.put("password", password);
        userMap.put("isCheck", isCheck);

        return userMap;
    }

    public static boolean insertUser(MySqlite sqlite, String user, String pass) {
        db = sqlite.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM user WHERE user = '" + user + "'", null);
        if (cursor.getCount() != 0) {
            db.close();
            return false;
        } else {
            db = sqlite.getWritableDatabase();
            values.put("user", user);
            values.put("pass", pass);
            db.insert("user", null, values);
            values.clear();
            db.close();
            return true;
        }
    }

    public static boolean selectUserAndPass(MySqlite sqlite, String user, String pass) {
        db = sqlite.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM user WHERE user = '" + user + "' and pass ='" + pass + "'", null);

        if (cursor.getCount() != 0) {
            db.close();
            return true;
        }
        return false;
    }
}
